import pymysql
from utils.base_response import BaseResponse


# 用于mysql的连接
class mySQL:
    def __init__(self, *args, **kwargs):
        self.res = BaseResponse()
        self.conn = self.get_conn(**kwargs)  # 账号密码等信息，建立连接
        self.cursor = self.get_cursor()  # 取数据为字典的游标

    # 建立连接
    def get_conn(self, **kwargs):
        try:
            conn = pymysql.connect(**kwargs)
        except Exception as e:
            self.res.status = 1
            self.res.msg = '数据库连接失败！'
            self.res.error = str(e.args)
        else:
            return conn

    # 获取游标
    def get_cursor(self):
        if self.res.status: return
        cursor_type = pymysql.cursors.DictCursor
        cursor = self.conn.cursor(cursor_type)
        return cursor

    # 执行sql,并得到结果
    def execute_select(self, sql):
        if self.res.status: return
        try:
            rows = self.cursor.execute(sql)  # 获取成功条数
            data = self.cursor.fetchall()  # 获取全部数据
            if isinstance(data, tuple) and len(data) == 0:
                data = []
        except Exception as e:
            rows = 0  # 获取成功条数
            data = []  # 获取全部数据
            self.res.status = 1
            self.res.data = sql
            self.res.msg = 'sql执行失败'
            self.res.error = str(e.args)
        return {'rows': rows, 'data': data, }

    # # 取回执行结果
    # def get_dict(self):
    #     return self.execute_dict

    # 关闭连接
    def close(self):
        if self.cursor:
            self.cursor.close()
        if self.conn:
            self.conn.close()


if __name__ == '__main__':
    aa = {'db': 'jiangsqobj2', 'host': '127.0.0.1', 'port': 3306, 'user': 'root', 'password': '', 'charset': 'utf8'}
    sql = '''
    SELECT 
    env.id,
    env.env_protocol,
    env.env_ip,
    env.env_port,
    env.env_title,
    env.token,
    env.`status` 
    FROM basics_environment env 
    WHERE env.`id` = 653
    '''
    obj = mySQL(**aa)
    data = obj.execute_select(sql)
    print(data)
